/*
** main.c for myls in /home/nadali_t//local/psu/myls
** 
** Made by thomas nadalie
** Login   <nadali_t@epitech.net>
** 
** Started on  Mon Oct 29 14:31:59 2012 thomas nadalie
** Last update Mon Oct 29 14:33:29 2012 thomas nadalie
*/

#include	<stdio.h>
#include        <sys/types.h>
#include	<sys/stat.h>
#include	<unistd.h>
#include	<stdlib.h>
#include	"my.h"

void		make_read(int ac, char **av, char *path)
{
  DIR           *dirp;
  struct dirent *d;
  const char    *name;

  if (path != '\0')
    name = path;
  else
    name = ".";
  dirp = opendir(name);
  if (dirp == NULL)
    my_put_error("Opendir function failed\n");
  d = readdir(dirp);
  if (d == NULL)
    my_put_error("Readdir function failed\n");
  make_read2(d, ac, av, dirp);
}

void		make_read2(struct dirent *d, int ac, char **av, DIR *dirp)
{
  t_list	*list;
  struct stat	sb;
  int		opt;

  if ((list = malloc(sizeof(*list))) == NULL)
    my_put_error("Malloc function failed\n");
  list = NULL;
  stat(d->d_name, &sb);
  fill_list(&list, sb, d);
  opt = check_opt(av, dirp, d, sb, &list);
  if (my_showlist(list, opt) != 1)
    no_options(d, dirp, sb, &list);
}

int		check_opt(char **av, DIR *dirp, struct dirent *d, struct stat sb, t_list **list)
{
  int		i;
  int		opt;
  int		ac;

  i = 0;
  opt = 0;
  ac = my_tablen(av);
  while (i < ac)
    {
      if (ac > 1)
	{
	  if (my_strcmp(av[i], "-l") == 0)
	    {
	      option_l(d, dirp, sb, list);
	      opt = 1;
	    }
	  else if (my_strcmp(av[i], "-a") == 0)
	    {
	      option_a(d, dirp, sb, list);
	      opt = 2;
	    }
 	}
      i++;
    }
 /*  else */
/*     my_putstr("USAGE : ./my_ls [-option] [-directory]\n"); */
  return (opt);
}

void	       	myls(int ac, char **av)
{
  int		i;
  char		*path;

  i = 0;
  while (av[i])
    {
      if (my_strcmp(av[i], "-") != 0)
	path = get_path(av[i]);
      i++;
    }
  make_read(ac, av, path);
}

int             main(int ac, char **av)
{
  if (ac > 1)
    myls(ac, av);
  return (0);
}
